//
//  MyOrderVC.m
//  saler-ios
//
//  Created by 王亚陆 on 17/5/27.
//  Copyright © 2017年 sayimba. All rights reserved.
//

#import "MyOrderVC.h"
#import "MineOrderModel.h"
#import "MyOrderCell.h"
#import "OrderDetailVC.h"
#define kNumber 5
#define defaultShow 10
//待付款
#define order_pendpaying @"pendpaying"
////待发车
//
//#define order_waitdeparture @"waitdeparture"

//待接单
#define order_waiting @"waiting"

//执行中
//intransit
#define order_intransit @"intransit"
//已交车

#define order_achieve @"completed"
//已完成
#define order_done @"done"

//全部
#define order_all @"all"

@interface MyOrderVC ()<UITableViewDelegate,UITableViewDataSource>
{
    UIView * nav;
}

@property (nonatomic) NSInteger  orderStatus;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *buttonArray;
@property (nonatomic,strong) NSMutableArray *imageArray;
@property (nonatomic,strong) NSMutableArray *dataArray;


@property (nonatomic) NSInteger number;
@property (nonatomic) int pageNo;
@property (nonatomic) NSInteger pageTotal;
@property (nonatomic) int pageSize;

@property (nonatomic,strong) UIView *netView;
@property (nonatomic,strong) WKProgressHUD *hud;
@property (nonatomic,strong) NullView *nullView;

@end

@implementation MyOrderVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    nav = [self createNavView];
    [self createNavTitle:@"我的订单"];
    [self.view addSubview:nav];
    
    _orderStatus = 10;
    
    _number = 0;
    self.pageNo = 1;
    self.pageSize = defaultShow;
    
    self.nullView = [[NullView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight  - 45 * kHeight) andTitle:@""];
    self.nullView.backgroundColor = UIviewBackColor;
    
    //创建无网络状态view
    self.netView = [UIView noInternet:@"网络连接失败，请检查网络设备" and:self action:@selector(NoNetPressBtn) andCGreck:CGRectMake(0, 0, Main_Width, Main_height-64)];
    
    self.buttonArray = [NSMutableArray array];
    self.dataArray = [[NSMutableArray alloc]init];
    
    self.imageArray = [NSMutableArray arrayWithObjects:@"1_press",@"1_unpress",@"3_press",@"3_unpress",@"4_press",@"4_unpress",@"2_press",@"2_unpress",@"5_press",@"5_unpress", nil];
    
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.view.backgroundColor = UIviewBackColor;
    
    [self initSubViews];

}

-(void)initSubViews
{
    
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, 45 * kHeight)];
    topView.backgroundColor = RGBACOLOR(252, 252, 252, 1);
    
    NSArray *titleArray = @[@"待审批",
                            @"待接单",
                            @"已接单",
                            @"已交车",
                            @"已收款"];
    
    for (int i = 0; i < titleArray.count; i++) {
        UIButton *topButton = [self backButtonWithString:titleArray[i] andInteger:i andView:topView];
        [topButton addTarget:self action:@selector(topButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        topButton.tag = i + 300;
        
        [self.buttonArray addObject:topButton];
        
        if (i == _number) {
            for (UILabel *lable in [topButton subviews]) {
                if ([lable isKindOfClass:[UILabel class]]) {
                    lable.textColor = BlueColor;
                    for (UIImageView *imageV in [lable subviews]) {
                        if ([imageV isKindOfClass:[UIImageView class]]) {
                            [UIView animateWithDuration:0.2 animations:^{
                                imageV.hidden = NO;
                                
                            }];
                        }
                    }
                }
            }
            for (UIImageView *img in [topButton subviews]) {
                if ([img isKindOfClass:[UIImageView class]]) {
                    img.image = [UIImage imageNamed:self.imageArray[_number]];
                }
            }
        }
    }
    

    [self.view addSubview:topView];

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Main_Width, 86*kHeight) style:UITableViewStylePlain];
    [self.tableView setTableFooterView:[UIView new]];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = UIviewBackColor;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left);
        make.top.mas_equalTo(topView.mas_bottom).with.offset(10*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width, Main_height-64-45 * kHeight-10*kHeight));
    }];

    
    //mj
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    
    //无网络状态
    [self createNetWorkAndStatue];
    
}


-(void)topButtonAction:(UIButton *)sender
{
    
    for (int i = 0; i < self.buttonArray.count; i++) {
        UIButton *button = (UIButton *)self.buttonArray[i];
        
        if (button.tag == sender.tag) {
            
            for (UIImageView *img in [sender subviews]) {
                if ([img isKindOfClass:[UIImageView class]]) {
                    img.image = [UIImage imageNamed:self.imageArray[(sender.tag - 300) * 2]];
                }
            }
            
            for (UILabel *lable in [sender subviews]) {
                
                if ([lable isKindOfClass:[UILabel class]]) {
                    
                    lable.textColor = BlueColor;
                    
                    for (UIImageView *imageV in [lable subviews]) {
                        
                        if ([imageV isKindOfClass:[UIImageView class]]) {
                            [UIView animateWithDuration:0.2 animations:^{
                                imageV.hidden = NO;
                            }];
                        }
                    }
                }
            }
        } else {
            
            for (UIImageView *img in [button subviews]) {
                if ([img isKindOfClass:[UIImageView class]]) {
                    img.image = [UIImage imageNamed:self.imageArray[i * 2 + 1]];
                }
            }
            
            for (UILabel *lable in [button subviews]) {
                if ([lable isKindOfClass:[UILabel class]]) {
                    
                    lable.textColor = littleBlackColor;
                    
                    for (UIImageView *imageV in [lable subviews]) {
                        
                        if ([imageV isKindOfClass:[UIImageView class]]) {
                            [UIView animateWithDuration:0.2 animations:^{
                                imageV.hidden = YES;
                                
                            }];
                        }
                    }
                }
            }
        }
    }
    
    [self present];
    
    _number = sender.tag - 300;
    self.pageNo = 1;
    
    [self initDataSource];
    
    
}

-(void)present
{
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    
//    NSString *string = [userDefaults objectForKey:@"login"];
//    
//    if (string == nil ) {
//        
//        LoginViewController *loginVC = [[LoginViewController alloc]init];
//        loginVC.topBackView.leftButton.hidden = YES;
//        UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
//        loginVC.backToFirst = @"1";
//        
//        [self presentViewController:loginNC animated:YES completion:nil];
//        
//    }
    
}


-(void)initDataSource

{

//    self.dataArray = nil;
    if (_number == 0) {
        self.nullView.label.text = @"暂无订单";
        _orderStatus = 10;

    } else if (_number == 1){
        self.nullView.label.text = @"暂无待接单";
        _orderStatus = 20;

        
    } else if (_number == 2){
        self.nullView.label.text = @"暂无已接单";
        _orderStatus = 30;
        
    } else if(_number == 3){
        self.nullView.label.text = @"暂无已交车";
        _orderStatus = 40;

    } else {
        self.nullView.label.text = @"暂无已收款";
        _orderStatus = 50;
    }
    
    
    NSString *string;
    NSString * auditStatus;
    if (_number == 0) {
        string = order_waiting;
        auditStatus = @"10,30";
    }
    
    if (_number == 1) {
        string = order_intransit;
        auditStatus = @"20";

    }
    
    if (_number == 2) {
        string = order_achieve;
        auditStatus = @"20";

    }
    
    if (_number == 3) {
        string = order_done;
        auditStatus = @"20";
    }
    
    if (_number == 4) {
        string = order_all;
        auditStatus = @"20&payStatus=30";
    }
    [WKProgressHUD showInView:self.view withText:@"" animated:YES];
    //pageNo   pageSize  userId  orderStatus  auditStatus

    //&auditStatus=10
    //订单状态接口
    NSString *urlString = nil;
    if (_number == 4) {
      urlString =  [NSString stringWithFormat:@"%@?pageNo=%d&pageSize=%d&auditStatus=%@",myOrder_list,self.pageNo,self.pageSize,auditStatus];
 
    }else{
        urlString =  [NSString stringWithFormat:@"%@?pageNo=%d&pageSize=%d&orderStatus=%ld&auditStatus=%@",myOrder_list,self.pageNo,self.pageSize,(long)_orderStatus,auditStatus];
    }
    
    
    [Common requestWithUrlString:urlString contentType:application_json finished:^(id responseObj) {
        
        [self.hud dismiss:YES];
        [WKProgressHUD dismissAll:YES];

        if ([responseObj[@"success"] boolValue]) {
            
            [WKProgressHUD dismissAll:YES];
            
            [self.hud dismiss:YES];
            
            NSMutableArray * arr = [NSMutableArray arrayWithArray:responseObj[@"data"][@"orderList"]];

            if (_pageNo == 1) {
                self.dataArray = nil;
                _dataArray = arr;
            }else{
                
                for (int i = 0; i<arr.count; i++) {
                    [self.dataArray addObject:arr[i]];
                }
            }
            
            
            if (self.dataArray.count >0) {
                
                [self.nullView removeFromSuperview];
                
            } else {
                
                [self.tableView addSubview:self.nullView];
                
            }
            
           _pageTotal = [responseObj[@"data"][@"page"][@"totalPage"] integerValue];

            [self.tableView reloadData];
            
        } else {
            
            [WKProgressHUD popMessage:responseObj[@"message"] inView:self.view duration:1.5 animated:YES];
        }
        
        
    } failed:^(NSString *errorMsg) {
        
        [WKProgressHUD dismissAll:YES];
        [self.hud dismiss:YES];

    }];
    
    
}


-(void)createNetWorkAndStatue{
    
    //判断是否有网
    [self judgeNetWork];
    //创建加载状态
}

//判断是否有网
-(void)judgeNetWork{
    if (![RLNetworkHelper isConnectedToNetwork]) {
        [self.tableView addSubview:self.netView];
        self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];
    }
    else{
        [self.netView removeFromSuperview];
        [self initDataSource];
    }
}


//无网络状态
-(void)NoNetPressBtn{
    if ([RLNetworkHelper isConnectedToNetwork]) {
        [self.netView removeFromSuperview];
        [self initDataSource];
    } else {
        [self.hud dismiss:YES];
    }
}

-(void)downRefresh{
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    self.pageNo = 1;
    
    [self judgeNetWork];
}
-(void)upRefresh{
    
    if (self.pageNo != (int)self.pageTotal) {
        self.pageNo ++;
        [self judgeNetWork];
        [self.tableView.mj_footer endRefreshing];
    }else{
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [self.tableView.mj_header endRefreshing];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 165*kHeight;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *string = @"fontCell";
    
    MyOrderCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (cell == nil) {
        cell = [[MyOrderCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell showInfo:_dataArray[indexPath.row]];
    
    if (_number == 0) {
        
        cell.payStatueLabel.hidden = YES;
        cell.pay.hidden = YES;
    }else{
        cell.payStatueLabel.hidden = NO;
        cell.pay.hidden = NO;

    }
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    OrderDetailVC * detail = [[OrderDetailVC alloc]init];
    detail.orderId = _dataArray[indexPath.row][@"id"];
    
    if (_number == 0) {
        detail.HideBtnImage = @"1";
    }
    
    detail.simbutSta = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.row][@"attachAuditStatus"]];
    
    [self.navigationController pushViewController:detail animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UIButton *)backButtonWithString:(NSString *)string andInteger:(int)a andView:(UIView *)view
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake( 15 + (screenWidth - 30)/kNumber * a, 0,(screenWidth - 30)/kNumber, 45 * kHeight);
    
    
    for (UIView *view in [button subviews]) {
        [view removeFromSuperview];
    }
    
//    UIImageView *logoImageV = [[UIImageView alloc]init];
//    logoImageV.backgroundColor = CyanColor;
//    [button addSubview:logoImageV];
//    [logoImageV mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.centerX.equalTo(button);
//        make.size.mas_equalTo(CGSizeMake(20, 20));
//        make.top.mas_equalTo(7 * kHeight);
//        
//    }];
//    logoImageV.image = [UIImage imageNamed:self.imageArray[2 * a + 1]];
//    
    UILabel *titleLabel = [[UILabel alloc]init];
    [button addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(button);
        make.width.equalTo(button);
        make.height.mas_equalTo(41 * kHeight - 20);
        make.centerY.equalTo(button);
        
    }];
    
    titleLabel.font = Font(FontOfSize13);
    titleLabel.textColor = BlackTitleColor;
    titleLabel.text = string;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [titleLabel sizeToFit];
    
    //    CGRect rect = titleLabel.frame;
    
    //下面黑线
    UIImageView *imageV = [[UIImageView alloc]init];
    [titleLabel addSubview:imageV];
    [imageV mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(button);
        make.height.mas_equalTo(1.5 * kHeight);
        make.width.mas_equalTo((screenWidth - 30)/4.0);
        make.centerX.mas_equalTo(button);
    }];
    
    imageV.backgroundColor = BlueColor;
    imageV.hidden = YES;
    [view addSubview:button];
    
    return button;
}


-(void)viewWillAppear:(BOOL)animated{
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:NO];
    
}

@end
